﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Security;
using System.Net.Sockets;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;

namespace IP2Client
{
    class ConnectionHandler
    {
        public static TcpClient HandledClient { get; set; }
        public static SslStream ClientSSLStream { get; set; }
        private static BinaryFormatter formatter = new BinaryFormatter();

        public static void SetupSSL(string strTargetAddress)
        {
            ClientSSLStream = new SslStream(HandledClient.GetStream(), true, new RemoteCertificateValidationCallback(ValidateServerCertificate));
            ClientSSLStream.AuthenticateAsClient(strTargetAddress);
        }

        /// <summary>
        /// Seems legit? Don't care.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="certificate"></param>
        /// <param name="chain"></param>
        /// <param name="sslPolicyErrors"></param>
        /// <returns></returns>
        public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }

        /// <summary>
        /// Method for sending an object to a TcpClient
        /// </summary>
        /// <param name="client">The TcpClient to send to</param>
        /// <param name="objectToSend">The object to send</param>
        public static void SendObject(object objectToSend)
        {
            try
            {
                formatter.Serialize(ClientSSLStream, objectToSend);
            }
            catch (Exception) { }
        }

        /// <summary>
        /// Method for reading an object from a TcpClient
        /// </summary>
        /// <param name="client"></param>
        /// <returns>An object</returns>
        public static object ReadObject()
        {
            object objTmp = null;

            try
            {
                objTmp = (object)formatter.Deserialize(ClientSSLStream);
            }
            catch (Exception)
            {
                ClientSSLStream.Close();
            }

            return objTmp;
        }
    }
}
